﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Local.Service;
using NReader.Model;
using NReader.Model.RAS;
using NReader.Service;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using XnReader.WinRT.Controlx;
using XnReader.WinRT.Helper;

// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234238 上有介绍

namespace XnReader.WinRT.Forms
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class FrameArticleList : Page
    {
        /// <summary>
        /// 存储当前书架ID
        /// </summary>
        private int _bookcaseid = -1;

        public FrameArticleList()
        {
            InitializeComponent();

        }

        /// <summary>
        /// 在此页将要在 Frame 中显示时进行调用。
        /// </summary>
        /// <param name="e">描述如何访问此页的事件数据。Parameter
        /// 属性通常用于配置页。</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var para = e.Parameter.ToString();
            if (!string.IsNullOrEmpty(para))
            {
                _bookcaseid = int.Parse(para);
                DataBinding(_bookcaseid);
            }
        }

        /// <summary>
        /// 动态绑定命令按钮
        /// </summary>
        /// <param name="bookcaseid"></param>
        private void DataBindingCommand(int bookcaseid)
        {
            var visiblesFooter = new CommandInfo
                                     {
                                         VisibleSearch = Visibility.Visible,
                                         VisibleImport = Visibility.Visible,
                                         VisibleClean = Visibility.Visible,
                                         VisibleDelete = Visibility.Visible,
                                         VisibleOnlineStore = Visibility.Visible
                                     };

            if (bookcaseid.Equals(0))
            {
                visiblesFooter.VisibleImport = Visibility.Collapsed;
                visiblesFooter.VisibleClean = Visibility.Collapsed;
                visiblesFooter.VisibleDelete = Visibility.Collapsed;
            }
            if (header != null)
            {
                header.DataContext = visiblesFooter;
                header.ImportClickEvent += ImportClickEvent;
                header.DeleteClickEvent += DeleteClickEvent;
                header.CleanClickEvent += CleanClickEvent;
            }
        }

        private ArticleListIncrementalLoadingClass<ArticleInfo> _articleList;

        private async void DataBinding(int bookcaseid)
        {
            pbLoading.IsActive = true;
            try
            {
                DataBindingCommand(bookcaseid);
                if (bookcaseid.Equals(0))
                    cvsArticleList.Source = await NReader.Service.GlobalService.Instance().GetHistory();
                else
                    cvsArticleList.Source = await NReader.Service.GlobalService.Instance().GetBookcases(bookcaseid);
            }
            catch (Exception ex)
            {
                var md = new MessageDialog(string.Format("书籍列表加载错误.错误信息为：\r\n{0}", ex.Message));
                md.ShowAsync();
            }
            finally
            {
                pbLoading.IsActive = false;
            }
        }

        #region import

        /// <summary>
        /// 缓存当前选中的文件
        /// </summary>
        private IReadOnlyList<StorageFile> _pickerFiles;

        /// <summary>
        /// 导入本地文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ImportClickEvent(object sender, RoutedEventArgs e)
        {
            var picker = new FileOpenPicker
                             {SuggestedStartLocation = PickerLocationId.PicturesLibrary, ViewMode = PickerViewMode.List};
            picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            picker.FileTypeFilter.Add(".txt");
            _pickerFiles = await picker.PickMultipleFilesAsync();

            if (_pickerFiles != null && _pickerFiles.Count > 0)
            {
                await Utils.CheckFolder("document");
                var folder = ApplicationData.Current.LocalFolder;
                var subfolder = await folder.GetFolderAsync("document");
                var maxid = await NReader.Service.ArticleService.Instance().GetArticleMaxID();

                if (_bookcaseid <= 0) return;

                //验证数量
                var count = await NReader.Service.ArticleService.Instance().GetBookStoreCountFromLocal(_bookcaseid);
                if ((count + _pickerFiles.Count) > 30)
                {
                    var md = new MessageDialog("选择的书架容量不够（上限30本）！");
                    await md.ShowAsync();
                    return;
                }
                pbLoading.IsActive = true;
                var errors = "";
                var catchMsg = "";
                foreach (var file in _pickerFiles)
                {
                    if (
                        await
                        NReader.Service.ArticleService.Instance().ExistsArticle(file.Name.Replace(file.FileType,
                                                                                                  string.Empty)))
                    {
                        errors += string.Format("{0};", file.Name);
                        continue;
                    }
                    //本地数据库处理
                    var article = new ArticleInfo
                                      {
                                          articleid = maxid,
                                          articlename = file.Name.Replace(file.FileType, string.Empty),
                                          online = 0,
                                          articletype = file.FileType,
                                          historyprogress = 0,
                                          updatetime = DateTime.Now.ToString("yyyyMMddHHmmss")
                                      };
                    if (await NReader.Service.ArticleService.Instance().AddBook(article) == false)
                    {
                        catchMsg += string.Format("{0};", file.Name);
                        continue;
                    }
                    if (
                        await
                        NReader.Service.ArticleService.Instance().AddBookStoreToLocal(article.articleid, _bookcaseid) ==
                        false)
                    {
                        catchMsg += string.Format("{0};", file.Name);
                        continue;
                    }
                    maxid++; //最大ID+1
                    //?san 判断文件是否存在未实现
                    //文件处理
                    file.CopyAsync(subfolder, file.Name, NameCollisionOption.ReplaceExisting);
                }
                pbLoading.IsActive = false;
                if (!string.IsNullOrEmpty(errors))
                {
                    errors += "\r\n文件已存在,请修改文件名后导入!";
                    if (!string.IsNullOrEmpty(catchMsg))
                    {
                        errors += catchMsg + "\r\n执行数据错误";
                    }
                    var md = new MessageDialog(errors);
                    await md.ShowAsync();
                }
               
                var rootFrame = Window.Current.Content as Frame;
                if (rootFrame != null) rootFrame.Navigate(typeof (BookcaseDx), _bookcaseid);

                #region 重新导入后，刷新章节页面缓存的数据

                ChapterIndex._article.articleid = 0;
                ChapterIndex._article.articlename = string.Empty;
                ChapterIndex._article.historyprogress = 0;
                ChapterIndex._article.historychapterid = 0;
                ChapterIndex._article.historychapter = "";
                ChapterIndex._posStart = 0;
                ChapterIndex._posEnd = 0;
                ChapterIndex._content = string.Empty;

                #endregion
            }
        }

        #endregion

        #region clean

        /// <summary>
        /// 清空书架
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void CleanClickEvent(object sender, RoutedEventArgs e)
        {
            if (itemGridView.Visibility == Visibility.Visible && itemGridView.Items.Count == 0)
                return;
            if (itemGridView.Items == null || itemGridView.Items.Count == 0) return;
            var messageDialog = new MessageDialog("确定清空当前书架的所有书籍?");
            messageDialog.Commands.Add(new UICommand("确定", new UICommandInvokedHandler(CommandInvokedHandler)));
            messageDialog.Commands.Add(new UICommand("取消", new UICommandInvokedHandler(CommandInvokedHandler)));
            messageDialog.DefaultCommandIndex = 0;
            messageDialog.CancelCommandIndex = 1;
            await messageDialog.ShowAsync();
        }

        #endregion

        #region delete


        /// <summary>
        /// 删除选中书籍
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void DeleteClickEvent(object sender, RoutedEventArgs e)
        {
            //if ((itemGridView.Visibility == Visibility.Visible && itemGridView.SelectedItems.Count == 0) ||
            //   (itemListView.Visibility == Visibility.Visible && itemListView.SelectedItems.Count == 0))
            //    return;
            if (itemGridView.Visibility == Visibility.Visible && itemGridView.Items.Count == 0) return;
            if (itemGridView.SelectedItems == null || itemGridView.SelectedItems.Count == 0) return;
            var messageDialog = new MessageDialog("确定删除当前选中的所有书籍?");
            messageDialog.Commands.Add(new UICommand("确定", new UICommandInvokedHandler(CommandDeleteInvokedHandler)));
            messageDialog.Commands.Add(new UICommand("取消", new UICommandInvokedHandler(CommandDeleteInvokedHandler)));
            messageDialog.DefaultCommandIndex = 0;
            messageDialog.CancelCommandIndex = 1;
            await messageDialog.ShowAsync();
        }

        #endregion

        #region Commands

        /// <summary>
        /// Callback function for the invocation of the dialog commands.
        /// </summary>
        /// <param name="command">The command that was invoked.</param>
        private async void CommandInvokedHandler(IUICommand command)
        {
            if (command.Label.Equals("确定"))
            {
                await DeleteFromBookcase(true);
            }
        }

        /// <summary>
        /// Callback function for the invocation of the dialog commands.
        /// </summary>
        /// <param name="command">The command that was invoked.</param>
        private async void CommandDeleteInvokedHandler(IUICommand command)
        {
            if (command.Label.Equals("确定"))
            {
                await DeleteFromBookcase(false);
            }
        }

        #endregion

        /// <summary>
        /// 从书架删除书籍
        /// </summary>
        /// <param name="isAll">全部删除</param>
        /// <returns></returns>
        private async Task DeleteFromBookcase(bool isAll)
        {
            IList<object> selectedItems = null;
            if (itemGridView.Visibility == Visibility.Visible)
            {
                selectedItems = isAll ? itemGridView.Items : itemGridView.SelectedItems;
            }
            //else
            //{
            //    selectedItems = isAll ? itemListView.Items : itemListView.SelectedItems;
            //}

            string errors = "";
            if (selectedItems != null && selectedItems.Count > 0)
            {
                foreach (ArticleInfo article in selectedItems)
                {
                    //本地文件，先删除文件后删除数据库
                    if (article.online.Equals(0))
                    {
                        try
                        {
                            var result =
                                await
                                ArticleService.Instance().DeleteDocument(string.Format("{0}{1}", article.articlename,
                                                                                       article.articletype));
                            if (!string.IsNullOrEmpty(result)) //删除资料失败
                            {
                                errors += string.Format("{0},异常信息:{1}", article.articlename, result);
                                continue;
                            }
                        }
                        catch (Exception ex)
                        {
                            errors += string.Format("{0},异常信息:{1}", article.articlename, ex.Message);
                            continue;
                            // throw;
                        }
                    }
                    //if (!await ArticleService.Instance().DeleteBookStore(article.articleid) ||
                    //    !await ArticleService.Instance().DeleteBook(article))
                    if (!await ArticleService.Instance().DeleteBookStore(article.articleid))
                    {
                        errors += string.Format("{0},数据异常", article.articlename);
                    }
                }

                if (!string.IsNullOrEmpty(errors))
                {
                    var md = new MessageDialog(errors);
                    await md.ShowAsync();
                }
                var rootFrame = Window.Current.Content as Frame;
                if (rootFrame != null) rootFrame.Navigate(typeof(BookcaseDx), _bookcaseid);
            }
        }

        private void ItemGridViewItemClick(object sender, ItemClickEventArgs e)
        {
            var item = e.ClickedItem as ArticleInfo;
            if (item != null)
            {
                //"跳转来源标记"+书籍ID+书名+上次阅读章节名称+上次阅读章节ID+阅读进度+是否在线 
                                var rootFrame = Window.Current.Content as Frame;
               
                //?san 作废 "跳转来源标记"+书籍ID
                if (item.online.Equals(0)) //本地导入的书籍."跳转来源标记"+书籍ID+书名+文件后缀名+阅读进度+上一章/下一章/当前章节+章节ID
                {
                    var param = string.Format("{0}|{1}|{2}|{3}|{4}|current|{5}", "offline",
                                              item.articleid,
                                              item.articlename,
                                              item.articletype,
                                             (decimal)item.historyprogress,
                                              item.historychapterid.Equals(0)
                                                  ? item.lastchapterid
                                                  : item.historychapterid);
                    if (rootFrame != null) rootFrame.Navigate(typeof(ChapterIndex), param); 
                }
                else
                {
                    var param = string.Format("{0}|{1}|{2}|{3}|{4}|current|{5}", "online",
                                              item.articleid,
                                              item.articlename,
                                              item.articletype,
                                             (decimal)item.historyprogress,
                                              item.historychapterid.Equals(0)
                                                  ? item.lastchapterid
                                                  : item.historychapterid);//历史阅读章节ID为空时，显示最新章节ID
                    if (!item.historychapterid.Equals(0))
                    {
                        if (rootFrame != null) rootFrame.Navigate(typeof(ChapterIndex), param); 
                    }
                    else
                    {
                        if (rootFrame != null) rootFrame.Navigate(typeof(Book), item.articleid); 
                        //直接加入书架还未点击阅读的书跳转到book页面
                    }
                }
            }
        }
    }

}
